package com.qf.ts.platform.front.realm;

import com.qf.ts.platform.commons.bean.User;
import com.qf.ts.platform.commons.constant.SystemParams;
import com.qf.ts.platform.front.service.UserService;
import com.qf.ts.platform.front.util.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: 一一哥
 * @Blame: yyg
 * @Since: Created in 2020/9/22
 * @Description: $cursor$
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        User user = userService.findUser(new User(username,password));
        if (user == null) {
            return null;
        }

        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.getSession().setAttribute("uid", user.getUuid());
        }

        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user = (User) super.getAvailablePrincipal(principalCollection);
        if(user==null){
            return null;
        }

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        List<String> roles=userService.selectRolesByUid(user.getId());
        info.addRoles(roles);

        List<String> permissions=userService.selectPermissionsByUid(user.getId());

        //List<String> newList=new ArrayList<>();
        //for(String item : permissions){
        //    if(item!=null){
        //        newList.add(item);
        //    }
        //}

        //item-->item!=null
        List<String> collect = permissions.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        //添加权限:注意:该权限的值是不能为null的!
        info.addStringPermissions(collect);

        return info;
    }

}
